package com.moon.service;

import com.moon.dao.TAuctionItemMapper;
import com.moon.dao.TAuctionMapper;
import com.moon.dao.THistoryMapper;
import com.moon.dao.TProductMapper;
import com.moon.dto.TUser;
import com.moon.entity.TAuction;
import com.moon.entity.TAuctionItem;
import com.moon.entity.THistory;
import com.moon.entity.TProduct;
import com.moon.es.EsDataWriter;
import com.moon.es.EsProductRepository;
import com.moon.utils.IdWorker;
import com.moon.utils.RedisLock;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class AuctionService {

    @Autowired
    TAuctionMapper auctionMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    TProductMapper productMapper;

    @Autowired
    private TAuctionItemMapper tAuctionItemMapper;

    @Autowired
    private THistoryMapper tHistoryMapper;

    @Autowired
    EsProductRepository esProductRepository;


    @Autowired
    @Qualifier("idWorker1")
    private IdWorker idWorker1;

    @Autowired
    @Qualifier("esProduct")
    EsDataWriter esDataWriter;

    private RedisLock redisLock = new RedisLock(new Jedis("localhost", 6379));

    @Transactional
    public String startAuction(TAuction auction) {
        redisLock.executeWithLock(()->{
            auction.setStartTime(new Date());
            //竞拍室状态设为 进行中
            auction.setStatus(1);
            Example example = new Example(TAuction.class);
            example.createCriteria().andEqualTo("id", auction.getId());
            auctionMapper.updateByExampleSelective(auction, example);

            //商品状态设为 正在竞拍中
            TProduct product = new TProduct();
            product.setStatus(1);
            Example example1 = new Example(TProduct.class);
            productMapper.updateByExampleSelective(product, example1);
            //更新ES数据
            esProductRepository.deleteAll();
            esDataWriter.dataWrite();

            rabbitTemplate.convertAndSend("delayAuctionExchange", "closeAuction", auction.toJson());
        });
        return "success";
    }

    @Transactional
    public void join(Long id, Long buyerId) {
        THistory tHistory=new THistory();
        tHistory.setId(idWorker1.nextId());
        tHistory.setUserId(buyerId);
        tHistory.setAuctionId(id);
        tHistoryMapper.insert(tHistory);

        TAuction tAuction = auctionMapper.selectByPrimaryKey(id);
        tAuction.setJoinCount(tAuction.getJoinCount()+1);
        auctionMapper.updateByPrimaryKey(tAuction);
    }
    @Transactional
    public String bidding(TAuction tAuction, TUser tUser, BigDecimal newPrice) {
        TAuctionItem tAuctionItem=new TAuctionItem();
        tAuctionItem.setId(idWorker1.nextId());
        tAuctionItem.setAuctionId(tAuction.getId());
        tAuctionItem.setBuyerId(tUser.getId());
        tAuctionItem.setNickname(tUser.getNickname());
        tAuctionItem.setAuctionPrice(newPrice);
        tAuctionItem.setCreateTime(new Date());

        tAuction.setBuyerId(tUser.getId());
        tAuction.setNickname(tUser.getNickname());
        tAuction.setTopPrice(newPrice);
        tAuction.setUpdateTime(new Date());

        synchronized(Long.toString(tAuction.getId()).intern()) {
            TAuction tAuction1 = auctionMapper.selectByPrimaryKey(tAuction.getId());
            if (tAuction.getTopPrice().compareTo(tAuction1.getTopPrice()) < 1) {
                return "已有更高的价格，请重新出价";
            }
            tAuctionItemMapper.insert(tAuctionItem);
            auctionMapper.updateByPrimaryKey(tAuction);
        }
        return "出价成功";
    }

    @Transactional
    public String insert(long productId, String basePrice, String stepPrice) {
        redisLock.executeWithLock(()->{
            TAuction auction = new TAuction();
            auction.setId(idWorker1.nextId());
            auction.setProductId(productId);
            auction.setBasePrice(new BigDecimal(basePrice));
            auction.setStepPrice(new BigDecimal(stepPrice));
            auction.setSecurityPrice(new BigDecimal(basePrice).multiply(new BigDecimal("0.05")));
            auction.setCreateTime(new Date());
            auction.setUpdateTime(new Date());
            auction.setStatus(0);
            auction.setJoinCount(0);
            auctionMapper.insert(auction);
            //更新ES数据
            esProductRepository.deleteAll();
            esDataWriter.dataWrite();
        });
        return "success";
    }
}
